package com.simtop.car.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.car.common.ServerResponse;
import com.simtop.car.mapper.SourceMapper;
import com.simtop.car.mapper.UserMapper;
import com.simtop.car.pojo.*;
import com.simtop.car.service.UserService;
import com.simtop.car.utils.AliyunMailUtil;
import com.simtop.car.utils.PythonUtil;
import com.simtop.car.utils.RedisUtil;
import com.simtop.car.utils.SmsRandomCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserServiceImpl implements UserService {

//    @Autowired
//    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    public RedisUtil redisUtil;

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    public UserMapper userMapper;


    @Autowired
    public SourceMapper sourceMapper;

    @Override
    public User login(User user) {
        return userMapper.login(user);
    }

    @Override
    public List<Role> getRole() {
        return userMapper.getRole();
    }

    @Override
    public ServerResponse<String> register(User user) {
        String checkCode = (String) redisUtil.get("email_" + user.getEmail());
        if (StringUtils.isEmpty(checkCode)) {
            return ServerResponse.createByErrorMsg("验证码已失效");
        } else if (!user.getCheckCode().equals(checkCode)) {
            return ServerResponse.createByErrorMsg("验证码错误");
        } else {
            user.setCreateTime(new Date());
            User checkEmail = userMapper.checkEmail(user.getEmail());
            if (ObjectUtils.isEmpty(checkEmail)) {
                User checkUsername=userMapper.checkUsername(user);
                if(ObjectUtils.isEmpty(checkUsername)){
                    int i = userMapper.register(user);
                    if (i != 0) {
                        return ServerResponse.createBySuccessMsg("注册成功");
                    } else {
                        return ServerResponse.createByErrorMsg("注册失败");
                    }
                }else{
                    return ServerResponse.createByErrorMsg("该用户名已存在");
                }

            } else {
                return ServerResponse.createByErrorMsg("该邮箱已经注册过了!");
            }

        }
    }


    /**
     * 邮箱验证
     *
     * @param email
     * @return
     */
    @Override
    public ServerResponse<String> generateCheckCode(String email) {
        synchronized (this) {
            //邮箱非空验证
            if (email == null || "".equals(email)) {
                return ServerResponse.createByErrorMsg("邮箱不能为空,请填入有效地址");
            }
            //生成随机的6位数字验证码
            String verificationCode = SmsRandomCodeUtil.generateRandomSixNum();
            Date date=new Date();
            DateFormat fmt = new SimpleDateFormat("yyyy年MM月dd日");
            String time=fmt.format(date);
            //调用邮箱发送
            Boolean status=AliyunMailUtil.sendMail(email, "注册验证码-大数据环境下竞争情报虚拟仿真实验", "您好！"+"<br>"+"&nbsp;&nbsp;&nbsp;&nbsp;欢迎进入大数据环境下竞争情报虚拟仿真实验环境，您本次注册的验证码为：" + verificationCode + "。"+"<br>"+"&nbsp;&nbsp;&nbsp;&nbsp;此验证码五分钟内有效，请及时完成注册流程。" + "<br>"
                    + "&nbsp;&nbsp;&nbsp;&nbsp;本邮件是系统自动发送的，请勿直接回复"
                    +"<p style='text-align:center;'>华东师范大学商业分析实验教学中心</p>"
                    +"<p style='text-align:center'>"+time+"</p>");
           redisUtil.set("email_" + email,verificationCode,300);
            if(status==false){
                return ServerResponse.createByErrorMsg("网络有问题，无法发送邮箱");
            }
//            redisTemplate.boundValueOps("email_" + email).set(verificationCode, 180, TimeUnit.SECONDS);
            // todo 发送的验证码拼接了之前的验证码？？ 获取content内容时候出现getContent现象
            // todo 2019年8月28日09:23:18 接口中屏蔽验证码
            return ServerResponse.createBySuccessMsg("发送验证码成功");
        }
    }

    /**
     * 忘记密码时候，根据邮箱返回验证码
     *
     * @param email
     * @return
     */
    @Override
    public ServerResponse<String> forgetSendEmailCode(String email) {
        //验证邮箱是否存在
        User resultCount = userMapper.checkEmail(email);
        if (ObjectUtils.isEmpty(resultCount)) {
            return ServerResponse.createByErrorMsg("邮箱不存在！");
        }
        //生成随机的验证码
        String verificationCode = SmsRandomCodeUtil.generateRandomSixNum();
        Date date=new Date();
        DateFormat fmt = new SimpleDateFormat("yyyy年MM月dd日");
        String time=fmt.format(date);
        //调用邮箱发送
         Boolean status=AliyunMailUtil.sendMail(email, "密码重置验证码-大数据环境下竞争情报虚拟仿真实验", resultCount.getUsername()+"，您好！"+"<br>"+"&nbsp;&nbsp;&nbsp;&nbsp;欢迎回来，您本次密码重置的验证码为：" + verificationCode + "。"+"<br>"
                 +"&nbsp;&nbsp;&nbsp;&nbsp;此验证码五分钟内有效，请及时重置密码。" + "<br>" + "&nbsp;&nbsp;&nbsp;&nbsp;本邮件是系统自动发送的，请勿直接回复！"
                 +"<p style='text-align:center;'>华东师范大学商业分析实验教学中心</p>"
                 +"<p style='text-align:center'>"+time+"</p>");
        //发送成功保存邮箱地址对应的验证码 todo 3分钟 已解决
        if(status==false){
            return ServerResponse.createByErrorMsg("网络有问题，无法发送邮箱");
        }
        redisUtil.set("forget_" + email,verificationCode,300);
//        redisTemplate.boundValueOps("forget_" + email).set(verificationCode, 300, TimeUnit.SECONDS);
        return ServerResponse.createBySuccessMsg("验证码已经发送");
    }

    /**
     * 修改密码
     *
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> updatePassword(User user) {
        String checkCode = (String) redisUtil.get("forget_" + user.getEmail());
//        String checkCode = redisTemplate.boundValueOps("forget_" + user.getEmail()).get();
        int updatePasswordResult = 0;
        if (StringUtils.isEmpty(checkCode)) {
            return ServerResponse.createByErrorMsg("验证码已经失效");
        } else {
            if (!checkCode.equals(user.getCheckCode())) {
                return ServerResponse.createByErrorMsg("验证码输入错误");
            } else {
                User checkEmailUser = userMapper.checkEmail(user.getEmail());
                if (!ObjectUtils.isEmpty(checkEmailUser)) {
                    updatePasswordResult = userMapper.updatePassword(user);
                }
            }
        }
        if (updatePasswordResult != 0) {
            return ServerResponse.createBySuccessMsg("修改成功");
        } else {
            return ServerResponse.createByErrorMsg("修改失败");
        }
    }

    @Override
    public ServerResponse<Grade> submitGrades(String[] brandType, User user, String[] word,Integer sourceCount,String ciYun,Integer questionNums,String answer) {
        Grade grade = new Grade();
        grade.setThemeObject(brandType[0]);
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < brandType.length; i++) {
            sb.append(brandType[i]).append(",");
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("微博", 0);
        map.put("微信", 0);
        map.put("新闻", 0);
        map.put("招聘", 0);
        map.put("专利", 0);
        map.put("企业官网", 0);
        map.put("社区论坛", 0);
        map.put("企业年报", 0);
        map.put("工商信息", 0);
        String uuid= (String) redisUtil.get("uuid"+user.getId());
        List<GradeNums> gradeNumsList = userMapper.getNums(user.getId(), brandType,uuid);
        gradeNumsList.forEach(gradeNums -> {
            map.put(gradeNums.getSource(), gradeNums.getNums());
        });
        int weiBoNums = map.get("微博");
        int weiXinNums = map.get("微信");
        int newsNums = map.get("新闻");
        int recruitmentNums = map.get("招聘");
        int patentNums = map.get("专利");
        int companyWebsiteNums = map.get("企业官网");
        int communityForumNums = map.get("社区论坛");
        int corporateAnnualReportsNums = map.get("企业年报");
        int businessInformationNums = map.get("工商信息");
        grade.setWeiBoNums(weiBoNums);
        grade.setWeiXinNums(weiXinNums);
        grade.setNewsNums(newsNums);
        grade.setRecruitmentNums(recruitmentNums);
        grade.setPatentNums(patentNums);
        grade.setCompanyWebsiteNums(companyWebsiteNums);
        grade.setCommunityForumNums(communityForumNums);
        grade.setCorporateAnnualReportsNums(corporateAnnualReportsNums);
        grade.setBusinessInformationNums(businessInformationNums);
        logger.info("词云{}",ciYun);
        grade.setCiYun(ciYun);
        int selfNums = weiBoNums + weiXinNums + newsNums + recruitmentNums + patentNums + companyWebsiteNums + communityForumNums + corporateAnnualReportsNums + businessInformationNums;
        int weiBoCountNums;
//        if (!redisUtil.hasKey("weiBoCountNums" + Arrays.toString(brandType))) {
            weiBoCountNums = userMapper.countNums("tb_weibo", brandType);
//            redisUtil.set("weiBoCountNums" + Arrays.toString(brandType),weiBoCountNums);
//        } else {
//            weiBoCountNums = (int) redisUtil.get("weiBoCountNums" + Arrays.toString(brandType));
//        }
        int weiXinCountNums;
//        if (!redisUtil.hasKey("weiXinCountNums" + Arrays.toString(brandType))) {
            weiXinCountNums = userMapper.countNums("tb_wechat", brandType);
//            redisUtil.set("weiXinCountNums" + Arrays.toString(brandType), weiXinCountNums);
//        } else {
//            weiXinCountNums = (int) redisUtil.get("weiXinCountNums" + Arrays.toString(brandType));
//        }
        int newsCountNums;
//        if (!redisUtil.hasKey("newsCountNums" + Arrays.toString(brandType))) {
            newsCountNums = userMapper.countNums("tb_news", brandType);
//            redisUtil.set("newsCountNums" + Arrays.toString(brandType), newsCountNums);
//        } else {
//            newsCountNums = (int) redisUtil.get("newsCountNums" + Arrays.toString(brandType));
//        }
        int recruitmentCountNums;
//        if (!redisUtil.hasKey("recruitmentCountNums" + Arrays.toString(brandType))) {
            recruitmentCountNums = userMapper.countNums("tb_recruitment", brandType);
//            redisUtil.set("recruitmentCountNums" + Arrays.toString(brandType), recruitmentCountNums);
//        } else {
//            recruitmentCountNums = (int) redisUtil.get("recruitmentCountNums" + Arrays.toString(brandType));
//        }
        int patentCountNums;
//        if (!redisUtil.hasKey("patentCountNums" + Arrays.toString(brandType))) {
            patentCountNums = userMapper.countNums("tb_patent", brandType);
//            redisUtil.set("patentCountNums" + Arrays.toString(brandType), patentCountNums);
//        } else {
//            patentCountNums = (int) redisUtil.get("patentCountNums" + Arrays.toString(brandType));
//        }
        int companyWebsiteCountNums;
//        if (!redisUtil.hasKey("companyWebsiteCountNums" + Arrays.toString(brandType))) {
            companyWebsiteCountNums = userMapper.countNums("tb_company_website", brandType);
//            redisUtil.set("companyWebsiteCountNums" + Arrays.toString(brandType), companyWebsiteCountNums);
//        } else {
//            companyWebsiteCountNums = (int) redisUtil.get("companyWebsiteCountNums" + Arrays.toString(brandType));
//        }
        int communityForumCountNums;
//        if (!redisUtil.hasKey("communityForumCountNums" + Arrays.toString(brandType))) {
            communityForumCountNums = userMapper.countNums("tb_community_forum", brandType);
//            redisUtil.set("communityForumCountNums" + Arrays.toString(brandType), communityForumCountNums);
//        } else {
//            communityForumCountNums = (int) redisUtil.get("communityForumCountNums" + Arrays.toString(brandType));
//        }
        int corporateAnnualReportsCountNums;
//        if (!redisUtil.hasKey("corporateAnnualReportsCountNums" + Arrays.toString(brandType))) {
            corporateAnnualReportsCountNums = userMapper.countNums("tb_corporate_annual_reports", brandType);
//            redisUtil.set("corporateAnnualReportsCountNums" + Arrays.toString(brandType), corporateAnnualReportsCountNums);
//        } else {
//            corporateAnnualReportsCountNums = (int) redisUtil.get("corporateAnnualReportsCountNums" + Arrays.toString(brandType));
//        }
        int businessInformationCountNums;
//        if (!redisUtil.hasKey("businessInformationCountNums" + Arrays.toString(brandType))) {
            businessInformationCountNums = userMapper.countNums("tb_business_information", brandType);
//            redisUtil.set("businessInformationCountNums" + Arrays.toString(brandType), businessInformationCountNums);
//        } else {
//            businessInformationCountNums = (int) redisUtil.get("businessInformationCountNums" + Arrays.toString(brandType));
//        }
        int countNums = weiBoCountNums + weiXinCountNums + newsCountNums + recruitmentCountNums + patentCountNums + companyWebsiteCountNums + communityForumCountNums + corporateAnnualReportsCountNums + businessInformationCountNums;
        grade.setAmountScore((int) (Math.round((double) selfNums) / ((double) countNums) * 50));
        int objectScore = (int) Math.round(((double) brandType.length - 1) / 7 * 30);

        int wordScore = 0;
        if(word.length!=1){
            wordScore=(int) Math.round(((double) word.length / sourceCount * 20));
        }
        grade.setWordCloudDisplayArray(word);
        grade.setWordScore(wordScore);
        grade.setObjectScore(objectScore);
        grade.setCompeteObject(sb.toString().substring(0, sb.toString().length() - 1));
        grade.setUserId(user.getId());
        grade.setUserName(user.getUsername());
        grade.setGradeDate(new Date());
        grade.setQuestionNums(questionNums);
        grade.setAnswer(answer);
        long time=(System.currentTimeMillis() - user.getLoginTime()) / 1000 / 60;
        if(time==0){
            grade.setExperimentalDuration(1);
        }else{
            grade.setExperimentalDuration((System.currentTimeMillis() - user.getLoginTime()) / 1000 / 60);
        }
        grade.setTotalScore(objectScore + wordScore + grade.getAmountScore());
        userMapper.submitGrades(grade);
        return ServerResponse.createBySuccess(grade);
    }


    @Override
    public void expertLogin(User expertLoginUser) {
        userMapper.expertLogin(expertLoginUser);
    }

    @Override
    public ServerResponse<String> submitComments(Integer gradeId, String comment) {
        Grade grade = new Grade();
        grade.setGradeId(gradeId);
        grade.setComment(comment);
        int i = userMapper.submitComments(grade);
        if (i != 0) {
            return ServerResponse.createBySuccess("成功添加评论");
        } else {
            return ServerResponse.createBySuccessMsg("添加评论失败");
        }
    }

    @Override
    public ServerResponse<PageInfo<Grade>> getGrade(Integer pageSize, Integer pageNum, User user) {
        if (StringUtils.isEmpty(pageNum)) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Grade> gradeList = userMapper.getGrade(user);
        PageInfo pageInfo = new PageInfo(gradeList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public Integer getUserNums() {
        return userMapper.getUserNums();
    }

    @Override
    public Integer getExperimentNums() {
        return userMapper.getExperimentNums();
    }

    @Override
    public Echarts3 selectScoreUser() {
        return userMapper.selectScoreUser();
    }

    @Override
    public List<Echarts2> selectRoleUser() {
        return userMapper.selectRoleUser();
    }

    @Override
    public ServerResponse<List> getLoyaltyIndex(User u, String[] brandType) {
        redisUtil.set(u.getId() + "experiment",System.currentTimeMillis());
        String uuid= (String) redisUtil.get("uuid"+u.getId());
//        redisTemplate.boundValueOps(u.getId() + "experiment").set(String.valueOf(System.currentTimeMillis()));
        List<LoyaltyIndex> loyaltyIndexList = userMapper.getLoyaltyIndex(u.getId(), brandType,uuid);
        for (int i = 0; i < loyaltyIndexList.size(); i++) {
            if (i <= 0) {
                loyaltyIndexList.get(i).setNums(100);
            } else if (i <= 2) {
                loyaltyIndexList.get(i).setNums(80);
            } else if (i <= 4) {
                loyaltyIndexList.get(i).setNums(60);
            } else if (i <= 7) {
                loyaltyIndexList.get(i).setNums(30);
            }
        }
        for (int i = 0; i < brandType.length; i++) {
            int status=0;
            for (int j = 0; j < loyaltyIndexList.size(); j++) {
                if(brandType[i].equals(loyaltyIndexList.get(j).getCarProduct())){
                    status=1;
                    break;
                }
            }
            if(status==0){
                LoyaltyIndex loyaltyIndex=new LoyaltyIndex();
                loyaltyIndex.setCarProduct(brandType[i]);
                loyaltyIndex.setNums(30);
                loyaltyIndexList.add(loyaltyIndex);
            }
        }
        return ServerResponse.createBySuccess(loyaltyIndexList);
    }


    @Override
    public ServerResponse getYield(String[] brandType) {
        List<LoyaltyIndex> yieldList = userMapper.getYield(brandType);
        int sum = yieldList.stream().mapToInt(LoyaltyIndex::getNums).sum();
        yieldList.forEach(yield -> {
            int nums = (int) (50 + Math.round((double) yield.getNums() / (double) sum * 0.5 * 45));
            yield.setNums((10 - nums % 10) + nums);
        });
        LoyaltyIndex loyaltyIndex=new LoyaltyIndex();
        loyaltyIndex.setCarProduct(brandType[0]);
        loyaltyIndex.setNums(50);
        if(!yieldList.contains(loyaltyIndex)){
            yieldList.add(loyaltyIndex);
        }
        return ServerResponse.createBySuccess(yieldList);
    }


    @Override
    public ServerResponse addExperiment(List<Experiment> experiment, User user) {
        experiment.forEach(experiment1 -> {
            experiment1.setUserId(user.getId());
        });
        int experimentStatus = userMapper.addExperiment(experiment);
        if (experimentStatus != 0) {
            return ServerResponse.createBySuccessMsg("成功添加实验数据");
        } else {
            return ServerResponse.createByErrorMsg("添加失败");
        }
    }

    @Override
    public ServerResponse addQuarter(Quarter quarter) {
        int quarterStatus = userMapper.addQuarter(quarter);
        if (quarterStatus != 0) {
            return ServerResponse.createBySuccessMsg("成功添加季度数据");
        } else {
            return ServerResponse.createByErrorMsg("添加失败");
        }
    }


    @Override
    public ServerResponse<List> getExperiment(Experiment experiment) {
        List<Experiment> returnExperimentList = userMapper.getExperiment(experiment);
        return ServerResponse.createBySuccess(returnExperimentList);
    }


    @Override
    public ServerResponse getQuarter(Quarter quarter) {
        Quarter returnQuarter = userMapper.getQuarter(quarter);
        returnQuarter.setQuarters(quarter.getQuarters());
        return ServerResponse.createBySuccess(returnQuarter);
    }


    @Override
    public ServerResponse<PageInfo> searchUser(Integer pageNum, Integer pageSize, String username) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.searchUser(username);
        PageInfo pageInfo = new PageInfo(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Override
    public ServerResponse deleteUser(Integer id) {
        int deleteStatus = userMapper.deleteUser(id);
        if (deleteStatus != 0) {
            return ServerResponse.createBySuccessMsg("成功删除该学生");
        } else {
            return ServerResponse.createByErrorMsg("删除该学生失败");
        }
    }


    @Override
    public ServerResponse getExperimentSum(User u, String brandType) {
        List<Experiment> experimentList = userMapper.getExperimentSum(u.getId(), brandType);
        Map<Integer, String> mapReplace = new HashMap<>();
        mapReplace.put(1, "small");
        mapReplace.put(2, "middle");
        mapReplace.put(3, "large");
        Map<String, Integer> map = new HashMap<>();
        experimentList.forEach(experiment -> {
            map.put(mapReplace.get(experiment.getMotorcycleType()), experiment.getProductPercent());
        });
        return ServerResponse.createBySuccess(map);
    }


    @Override
    public ServerResponse getLine(String[] brandType, Integer competitionId, User user) {
        Map<String, Integer> brandTypeMap = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < brandType.length; i++) {
            map.put(brandType[i], "");
            brandTypeMap.put(brandType[i], 10);
        }
        String jsonObject;
        if (competitionId == 1) {
            List<News> newsList = userMapper.getNews(brandType);
            newsList.forEach(news -> {
                if (!StringUtils.isEmpty(news)) {
                    String description = map.get(news.getCarProduct());
                    StringBuilder sb = new StringBuilder();
                    sb.append(description).append(news.getMainBody());
                    map.put(news.getCarProduct(), sb.toString()).replaceAll("#", "");
                    Integer nums = brandTypeMap.get(news.getCarProduct());
                    brandTypeMap.put(news.getCarProduct(), ++nums);
                }
            });
            List<CorporateAnnualReports> corporateAnnualReportsList = userMapper.getCorporateAnnualReports(brandType);
            corporateAnnualReportsList.forEach(corporateAnnualReports -> {
                if (!StringUtils.isEmpty(corporateAnnualReports)) {
                    String description = map.get(corporateAnnualReports.getCarProduct());
                    StringBuilder sb = new StringBuilder();
                    sb.append(description).append(corporateAnnualReports.getAnnualReport()).append(corporateAnnualReports.getAnnualReportInFull());
                    map.put(corporateAnnualReports.getCarProduct(), sb.toString()).replaceAll("#", "");
                    Integer nums = brandTypeMap.get(corporateAnnualReports.getCarProduct());
                    brandTypeMap.put(corporateAnnualReports.getCarProduct(), ++nums);
                }
            });
        } else if (competitionId == 2) {
            List<Patent> patentList = userMapper.getPatent(brandType);
            patentList.forEach(patent -> {
                if (!StringUtils.isEmpty(patent)) {
                    String description = map.get(patent.getCarProduct());
                    StringBuilder sb = new StringBuilder();
                    sb.append(description).append(patent.getAbstracts()).append(patent.getDescription());
                    map.put(patent.getCarProduct(), sb.toString()).replaceAll("#", "");
                    Integer nums = brandTypeMap.get(patent.getCarProduct());
                    brandTypeMap.put(patent.getCarProduct(), ++nums);
                }
            });
        } else if (competitionId == 3) {
            List<CompanyWebsite> companyWebsiteList = userMapper.getCompanyWebsite(brandType);
            companyWebsiteList.forEach(companyWebsite -> {
                if (!StringUtils.isEmpty(companyWebsite)) {
                    String description = map.get(companyWebsite.getCarProduct());
                    StringBuilder sb = new StringBuilder();
                    sb.append(description).append(companyWebsite.getProductName()).append(companyWebsite.getProductDescription());
                    map.put(companyWebsite.getCarProduct(), sb.toString()).replaceAll("#", "");
                    Integer nums = brandTypeMap.get(companyWebsite.getCarProduct());
                    brandTypeMap.put(companyWebsite.getCarProduct(), ++nums);
                }
            });
        } else if (competitionId == 4) {
            for (Map.Entry<String, Integer> entry : brandTypeMap.entrySet()) {
                Integer nums = userMapper.getBrandTypeNums(entry.getKey(), "tb_weibo");
                Integer value = entry.getValue() + nums;
                brandTypeMap.put(entry.getKey(), value);
                List<String> weiBoList = userMapper.getWeiBo(entry.getKey());
                StringBuilder sb = new StringBuilder();
                sb.append(String.join(",", weiBoList).replaceAll("#", ""));
                map.put(entry.getKey(), sb.toString());
            }
            for (Map.Entry<String, Integer> entry : brandTypeMap.entrySet()) {
                Integer nums = userMapper.getBrandTypeNums(entry.getKey(), "tb_community_forum");
                brandTypeMap.put(entry.getKey(), entry.getValue() + nums);
                List<String> communityForumList = userMapper.getCommunityForum(entry.getKey());
                StringBuilder sb = new StringBuilder();
                sb.append(String.join(",", communityForumList).replaceAll("#", ""));
                map.put(entry.getKey(), sb.toString());
            }
        } else if (competitionId == 5) {
            List<WeChat> weChatList = userMapper.getWechat(brandType);
            List<News> newsList = userMapper.getNews(brandType);
            newsList.forEach(news -> {
                if (!StringUtils.isEmpty(news)) {
                    String description = map.get(news.getCarProduct());
                    StringBuilder sb = new StringBuilder();
                    sb.append(description).append(news.getMainBody());
                    map.put(news.getCarProduct(), sb.toString()).replaceAll("#", "");
                    Integer nums = brandTypeMap.get(news.getCarProduct());
                    brandTypeMap.put(news.getCarProduct(), ++nums);
                }
            });
            weChatList.forEach(weChat -> {
                if (!StringUtils.isEmpty(weChat)) {
                    String description = map.get(weChat.getCarProduct());
                    StringBuilder sb = new StringBuilder();
                    sb.append(description).append(weChat.getMainBody());
                    map.put(weChat.getCarProduct(), sb.toString()).replaceAll("#", "");
                    Integer nums = brandTypeMap.get(weChat.getCarProduct());
                    brandTypeMap.put(weChat.getCarProduct(), ++nums);
                }
            });
        }
        StringBuilder pythonSB = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String regEx = "[\n`~@!$%^&*()+=|丨{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？]";
            String aa = "";//这里是将特殊字符换为aa字符串,""代表直接去掉
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(entry.getValue());//这里把想要替换的字符串传进来
            String newString = m.replaceAll(aa).trim();
            if (newString.length() >= 1000) {
                pythonSB.append(entry.getKey()).append("!").append(newString.substring(0, 1000)).append("#");
            } else {
                pythonSB.append(entry.getKey()).append("!").append(newString.substring(0, newString.length())).append("#");
            }
        }
        String s = pythonSB.toString().replaceAll("\\\\", "");
        jsonObject = PythonUtil.getLine(s.replaceAll("\"", ""));
        Integer sum = 0;
        for (String key : brandTypeMap.keySet()) {
            sum += brandTypeMap.get(key);
        }
        for (String key : brandTypeMap.keySet()) {
            brandTypeMap.put(key, (int) ((double) brandTypeMap.get(key) / (double) sum * 100));
        }
        Lines lines = new Lines();
        lines.setLines(jsonObject);
        List<Nodes> nodesList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : brandTypeMap.entrySet()) {
            Nodes nodes = new Nodes();
            nodes.setName(entry.getKey());
            nodes.setValue(entry.getValue());
            nodesList.add(nodes);
        }
        lines.setNodes(nodesList);
        return ServerResponse.createBySuccess(lines);
    }


    @Override
    public ServerResponse getScaleGrade(User u) {
        List<Experiment> experimentList = userMapper.getScaleGrade(u.getId());
        long experiment = (long) redisUtil.get(u.getId() + "experiment");
//        long experiment = Long.parseLong(redisTemplate.boundValueOps(u.getId() + "experiment").get());
        ScaleGrade scaleGrade = new ScaleGrade();
        scaleGrade.setExperimentList(experimentList);
        scaleGrade.setExperimentTime((int) ((System.currentTimeMillis() - experiment) / 1000 / 60));
        return ServerResponse.createBySuccess(scaleGrade);
    }

    @Override
    public ServerResponse commitScaleGrade(Integer gradeId, Integer scaleScore,String simulation,Integer aggregateAmount) {
        int scaleGradeStatus = userMapper.commitScaleGrade(gradeId, scaleScore,simulation,aggregateAmount);
        if (scaleGradeStatus != 0) {
            return ServerResponse.createBySuccess("成功提交仿真实验成绩报告");
        } else {
            return ServerResponse.createByErrorMsg("提交失败");
        }
    }


    @Override
    public List<Grade> exportExperimentGrade(User user) {
        return userMapper.exportExperimentGrade(user);
    }

    @Override
    public ServerResponse addQuestion(Question question, Integer id) {
        question.setQuestionUserId(id);
        Integer addQuestionStatus=userMapper.addQuestion(question);
        if(addQuestionStatus!=0){
            return ServerResponse.createBySuccessMsg("成功添加问题");
        }else{
            return ServerResponse.createByErrorMsg("添加问题失败");
        }
    }

    @Override
    public ServerResponse addAnswer(Answer answer, Integer id) {
        answer.setAnswerUserId(id);
        Integer addAnswerStatus=userMapper.addAnswer(answer);
        if(addAnswerStatus!=0){
            return ServerResponse.createBySuccessMsg("成功添加评论");
        }else{
            return ServerResponse.createByErrorMsg("添加评论失败");
        }
    }

    @Override
    public ServerResponse deleteAnswer(Integer answerId,User user) {
        Integer deleteAnswerStatus=userMapper.deleteAnswer(answerId,user.getRoleId(),user.getId());
        if(deleteAnswerStatus!=0){
            return ServerResponse.createBySuccessMsg("成功删除该评论");
        }else{
            return ServerResponse.createByErrorMsg("删除该评论失败");
        }
    }


    @Transactional
    @Override
    public ServerResponse deleteQuestion(Integer questionId) {
        Integer deleteQuestionStatus=userMapper.deleteQuestion(questionId);
        userMapper.deleteALLAnswer(questionId);
        if(deleteQuestionStatus!=0){
            return ServerResponse.createBySuccessMsg("成功删除该问题");
        }else{
            return ServerResponse.createByErrorMsg("删除该问题失败");
        }
    }

    @Override
    public ServerResponse getAnswer(Integer questionId) {
        List<Answer> questionList=userMapper.getAnswer(questionId);
        return ServerResponse.createBySuccess(questionList);
    }

    @Override
    public ServerResponse getQuestion(Integer pageNum, Integer pageSize, String username, String school, String question) {
        PageHelper.startPage(pageNum,pageSize);
        List<Question> questionList=userMapper.getQuestion(username,school,question);
        questionList.forEach(question1 -> {
           List<Answer> answerList=userMapper.getAnswer(question1.getQuestionId());
           if(answerList.size()==0){
               question1.setExists(false);
           }else{
               question1.setExists(true);
           }
        });
        PageInfo<Question> questionPageInfo=new PageInfo<>(questionList);
        return ServerResponse.createBySuccess(questionPageInfo);
    }

    @Override
    public List<WeiBo> getWeiboSourceData() {
        return userMapper.getWeiboSourceData();
    }

    @Override
    public List<WeChat> getWeChatSourceData() {
        return userMapper.getWeChatSourceData();
    }


    @Override
    public List<News> getNewsSourceData() {
        return userMapper.getNewsSourceData();
    }


    @Override
    public List<Recruitment> getRecruitmentSourceData() {
        return userMapper.getRecruitmentSourceData();
    }

    @Override
    public List<Patent> getPatentSourceData() {
        return userMapper.getPatentSourceData();
    }

    @Override
    public List<CompanyWebsite> getCompanyWebsiteSourceData() {
        return userMapper.getCompanyWebsiteSourceData();
    }

    @Override
    public List<CommunityForum> getCommunityForumSourceData() {
        return userMapper.getCommunityForumSourceData();
    }


    @Override
    public List<CorporateAnnualReports> getCorporateAnnualSourceData() {
        return userMapper.getCorporateAnnualSourceData();
    }

    @Override
    public List<BusinessInformation> getBusinessInformationSourceData() {
        return userMapper.getBusinessInformationSourceData();
    }
}
